package com.eraasoftware.npa.server;

import java.util.NoSuchElementException;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class ServiceListenerBlockingQueueImpl implements ServiceListenerPool {
	int MAX = 15;
	int MAX_WAIT = 4;

	// ArrayBlockingQueue<ServiceListener>(MAX, true);//
	LinkedBlockingQueue<ServiceListener> queue = new LinkedBlockingQueue<ServiceListener>();
	AtomicInteger nbServices = new AtomicInteger();

	@Override
	public ServiceListener getService() throws NoSuchElementException, IllegalStateException, InterruptedException {
		return queue.poll(MAX_WAIT, TimeUnit.SECONDS);
	}

	@Override
	public void returnObject(ServiceListener service) {

		if (service != null) {
			if (service.valid())
				queue.add(service);
			else {
				destroy(service);
			}
		}

	}

	@Override
	public void destroy(ServiceListener service) {
		System.out.println("DEsTroy");
		service.valid(false);
		queue.remove(service);
		service = null;
		nbServices.decrementAndGet();
	}

	@Override
	public int needClients() {
		// return queue.size()==0;
		if (queue.size() == 0 && nbServices.get() < MAX) {
			return 1;
		} else {
			return 0;
		}

	}

	@Override
	public void addNewService(ServiceListener serviceListener) throws Exception {
		queue.add(serviceListener);

		nbServices.incrementAndGet();

	}

	@Override
	public int availableServices() {
		return queue.size();
	}

}
